﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.Entity;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using IEstate.Web.Models;
using IEstate.Core.Models;
using IEstate.Repositories.Database;
using IEstate.Repositories;

namespace IEstate.Web.Controllers
{
    public class HomeController : Controller
    {
        private EstateContext DBContext = new EstateContext();
        private ApplicationDbContext DB = new ApplicationDbContext();

        [Authorize(Users="anastasia")]
        public ActionResult Check()
        {
            var query = DBContext.Estates.Where(p => DbFunctions.DiffDays(p.Date, DateTime.Now) > Global.DayLimit);
            
            // DbFunctions.DiffHours(o.ClientDateTimeStamp, clientDateTime) < 24
            
            foreach(var i in query) {
                DBContext.Estates.Remove(i);
            }

            DBContext.SaveChanges();

            return RedirectToAction("Index");
        }

        //
        // Display estates by City
        public ActionResult City(string City)
        {
            ViewBag.City = City;
            var query = DBContext.Estates.Where(p => String.Compare(p.City, City) == 0);
            return View("City", query);
        }

        public ActionResult Index()
        {
            return View("Index", DBContext.Estates);
        }

        //
        // Display estates by Category
        public ActionResult Category(Category category)
        {
            ViewBag.category = category;
            var query = DBContext.Estates.Where(p => p.TypeCategory == category);
            return View("Category", query);
        }

        //
        // Display estate by user's id
        public ActionResult GetDetails(int id = 1)
        {
            IEnumerable<Estate> query;

            query = DBContext.Estates.Where(p => p.UID == id);
            ViewBag.id = id;

            return View("GetDetails", query);
        }

        //
        // Search form - GET
        [HttpGet]
        public ActionResult xSearch(int? minPrice, int? maxPrice, int? bedrooms,
                                    Category? category, Option? option,
                                    Order? order)
        {
            if (minPrice != null || maxPrice != null || bedrooms != null || category != null || option != null)
                ViewBag.Code = true;

            IEnumerable<Estate> query = DBContext.Estates;

            if (minPrice != null)    query = query.Where(p => p.Price >= minPrice);
            if (maxPrice != null)    query = query.Where(p => p.Price <= maxPrice);
            if (category != null)    query = query.Where(p => p.TypeCategory == category);
            if (option != null)      query = query.Where(p => p.TypeOption == option);
            if (bedrooms != null)    query = query.Where(p => p.Bedrooms == bedrooms);
            if (order == Order.asc)  query = query.OrderBy(p => p.Price);
            if (order == Order.desc) query = query.OrderByDescending(p => p.Price);

            return View("xSearch", query);
        }

        //
        // Add estate
        [Authorize]
        public ActionResult Add()
        {
            return View("Add", new EstateViewModel());
        }

        [Authorize]
        [HttpPost]
        public ActionResult Add(EstateViewModel estateViewModel, HttpPostedFileBase image)
        {
            if (estateViewModel.Bedrooms == null)
            {
                ViewBag.Message = "Please fill bedrooms";
                return View("Add");
            }
            if (!ModelState.IsValid) return View("Add");

            var userId = User.Identity.GetUserId();
            var result = DB.Users.FirstOrDefault(p => p.Id == userId);

            var query = DBContext.Estates.Max(p => p.EstateID);
            ViewBag.id = query + 1;

            var iquery = DBContext.EImages.Where(p => p.EstateID == query + 1).Count();
            ViewBag.value = iquery + 1;

            Estate estate = new Estate
            {
                Street = estateViewModel.Street,
                Bedrooms = (int)estateViewModel.Bedrooms,
                Size = (int)estateViewModel.Size,
                Price = (int)estateViewModel.Price,
                UID = (int)result.userCode,
                Date = DateTime.Now,
                TypeCategory = estateViewModel.Category,
                TypeOption = estateViewModel.Option,
                City = estateViewModel.City
            };

            EImage Image = new EImage();

            if(image != null)
            {
                Image.EstateID = query + 1;
                Image.ImageMimeType = image.ContentType;
                Image.ImageData = new byte[image.ContentLength];
                image.InputStream.Read(Image.ImageData, 0, image.ContentLength);
            }

            if (image == null) ViewBag.Image = true;

            Approved approvedEstate = new Approved
            {
                Street = estate.Street,
                Bedrooms = estate.Bedrooms,
                Size = estate.Size,
                Price = estate.Price,
                UID = estate.UID,
                Date = DateTime.Now,
                TypeCategory = estate.TypeCategory,
                TypeOption = estate.TypeOption,
                City = estate.City
            };

            DBContext.Approved.Add(approvedEstate);
            DBContext.SaveChanges();

            DBContext.EImages.Add(Image);
            DBContext.SaveChanges();

            return View("_Add", estateViewModel);
        }

        //
        // Display image by Id and number
        public FileContentResult GetImage(int id = 1, int value = 1)
        {
            var iquery = DBContext.EImages.Where(p => p.EstateID == id);

            int counter = 1;

            if (iquery == null)
                return null;

            foreach(var i in iquery)
            {
                if (counter == value)
                    return File(i.ImageData, i.ImageMimeType);
                counter = counter + 1;
            }

            return null;
        }

        //
        // Most viewed estates
        public ActionResult MostViewed()
        {
            var query = DBContext.Estates.OrderByDescending(p => p.Views).Take(Global.MostViewedLimit);
            return View("MostViewed", query);
        }

        //
        // Display estate by Id
        public ActionResult Details(int id = 1)
        {
            var query = DBContext.Estates.FirstOrDefault(p => p.EstateID == id);
            query.Views = query.Views + 1;
            ViewBag.Id = id;

            DBContext.SaveChanges();

            if (query.Info == null) 
                ViewBag.Content = null;
            else 
                ViewBag.Content = query.Info;
            
            int userID = query.UID;
            var user = DB.Users.Where(p => p.userCode == userID).FirstOrDefault();
            
            ViewBag.user = user.UserName;
            ViewBag.phone = user.Phone;

            int number = DBContext.EImages.Count(p => p.EstateID == id);
            ViewBag.number = number;
            ViewBag.id = id;

            return View("Details", query);
        }

        //
        // About 
        public ActionResult About()
        {
            ViewBag.Message = "Real Estate MVC is a demo application to show off how great ASP.NET MVC is :)";

            return View();
        }

        //
        // Contact
        public ActionResult Contact()
        {
            ViewBag.Message = "Find admin's phone in user listening and call there";

            return View();
        }

        public PartialViewResult DisplayPromotional()
        {
            var query = DBContext.Estates.Where(p => p.Promotional == true);
            return PartialView("DisplayPromotional", query);
        }
    }
}